package com.haima.sage.bigdata.api.frame.process;

import java.util.ArrayList;
import java.util.List;

import com.haima.sage.bigdata.api.entity.api.Api;
import com.haima.sage.bigdata.api.frame.process.impl.DbApiProcess;
import com.haima.sage.bigdata.api.frame.process.impl.EsApiProcess;
import com.haima.sage.bigdata.api.frame.process.impl.MultiApiProcess;
import com.haima.sage.bigdata.api.frame.process.impl.RedisApiProcess;
import com.haima.sage.bigdata.api.entity.api.data.ApiData;
import com.haima.sage.bigdata.api.entity.api.data.cases.Case;
import com.haima.sage.bigdata.api.entity.api.data.cases.ConfigType;

import static com.haima.sage.bigdata.api.entity.api.data.cases.ConfigType.DB;

public class ApiProcessFactory {

    public static ApiProcess getInstance(Api api, ApiData data) throws Exception {
        if (api == null) {
            throw new IllegalArgumentException("api empty");
        }
        if (api.getData() == null || api.getData().length() == 0) {
            throw new IllegalArgumentException("api data empty");
        }
        try {
            if (data.getCases() == null || data.getCases().size() == 0) {
                throw new IllegalArgumentException("api data.cases empty");
            }
            if (data.getCases().size() == 1) {
                return getApiService(api, data, data.getCases().get(0));
            }
            data.getCases().sort((a, b) -> {
                if (a.isConditionEmpty()) {
                    return -1;
                }
                if (b.isConditionEmpty()) {
                    return -1;
                }
                return 0;
            });
            List<ApiProcess> list = new ArrayList<>();
            for (Case item : data.getCases()) {
                ApiProcess service = getApiService(api, data, item);
                list.add(service);
            }
            return MultiApiProcess.build(api, list);
        } catch (Exception e) {
            throw new Exception("get api service error", e);
        }
    }

    private static ApiProcess getApiService(Api api, ApiData data, Case item) throws Exception {
        ConfigType type = item.getConfig().getType() ;
        if (item.getConfig().getType() == null) {
            type = DB;
        }
        switch (type) {
            case ES:
                return EsApiProcess.build(api, data, item);
            case Redis:
                return RedisApiProcess.build(api, data, item);
            case DB:
            default:
                return DbApiProcess.build(api, data, item);
        }
    }
}
